<template>
  <view class="container">
    <!-- 用户信息 -->
    <view v-if="hadLogin" class="userinfo">
      <view class="userinfo-con">
        <view class="userinfo-avatar">
          <button
            class="avatar-wrapper"
            :class="{ 'image-error': !avatarLoaded }"
            open-type="chooseAvatar"
            style="width: 100%; height: 100%;padding: 0"
            @chooseavatar="onChooseAvatar"
          >
            <image
              :src="loginResult.pic ? loginResult.pic : '@/static/images/icon/head04.png'"
              class="avatar"
              style="width: 100%; height: 100%;"
              mode="aspectFill"
            />
          </button>
        </view>
        <view class="userinfo-name">
          <input
            type="nickname"
            class="nickname-input"
            :value="loginResult.nickName || '用户昵称'"
            placeholder="请输入昵称"
            @blur="onNicknameBlur"
            @confirm="onNicknameBlur"
          />
          <!-- <view class="user-status" v-if="loginResult.vipLevel > 0">
            <text class="vip-badge">VIP{{ loginResult.vipLevel }}</text>
          </view> -->
          <view class="welcome-text">欢迎回来！</view>
        </view>
      </view>
    </view>

    <view v-if="!hadLogin" class="userinfo-none">
      <view class="default-pic" @tap="toLogin">
        <image src="@/static/images/icon/head04.png" mode="aspectFill" />
      </view>
      <view class="none-login" @tap="toLogin">
        <button class="unlogin">未登录</button>
        <button class="click-login">点击登录账号</button>
      </view>
    </view>
    <!-- end 用户信息 -->

    <view class="list-cont">
      <!-- 订单状态 -->
      <view class="total-order">
        <view class="order-tit">
          <text style="font-weight: bold"> 我的订单 </text>
          <view class="checkmore" data-sts="0" @tap="toOrderListPage">
            <text>查看全部</text>
            <text class="arrowhead" />
          </view>
        </view>
        <view class="procedure">
          <view class="items" data-sts="1" @tap="toOrderListPage">
            <image src="@/static/images/icon/toPay.png" />
            <text>待支付</text>
            <text v-if="orderAmount.unPay > 0" class="num-badge">
              {{ orderAmount.unPay }}
            </text>
          </view>
          <view class="items" data-sts="2" @tap="toOrderListPage">
            <image src="@/static/images/icon/toDelivery.png" />
            <text>待检测</text>
            <text v-if="orderAmount.payed > 0" class="num-badge">
              {{ orderAmount.payed }}
            </text>
          </view>
          <view class="items" data-sts="3" @tap="toOrderListPage">
            <image src="@/static/images/icon/toTake.png" />
            <text>待确认</text>
            <text v-if="orderAmount.consignment > 0" class="num-badge">
              {{ orderAmount.consignment }}
            </text>
          </view>
          <view class="items" data-sts="5" @tap="toOrderListPage">
            <image src="@/static/images/icon/toComment.png" />
            <text>已完成</text>
          </view>
        </view>
      </view>
      <!--end 订单状态 -->

      <view class="prod-col">
        <view class="col-item" @tap="myCollectionHandle">
          <view v-if="loginResult" class="num">
            {{ collectionCount }}
          </view>
          <view v-else class="num"> -- </view>
          <view class="tit"> 我的收藏 </view>
        </view>
        <!-- <view class="col-item" @tap="handleTips">
          <view v-if="loginResult" class="num">
            5
            <text class="notification-dot" v-if="unreadMessages > 0"></text>
          </view>
          <view v-else class="num">
            --
          </view>
          <view class="tit">
            我的消息
          </view>
        </view>
        <view class="col-item" @tap="handleTips">
          <view v-if="loginResult" class="num">
            3
          </view>
          <view v-else class="num">
            --
          </view>
          <view class="tit">
            我的足迹
          </view>
        </view> -->
      </view>

      <view class="my-menu">
        <!-- <view class="memu-item" @tap="toCouponCenter">
          <view class="i-name">
            <image src="@/static/images/icon/getCoupon.png" />
            <text>领券中心</text>
          </view>
          <view class="arrowhead" />
        </view> -->
        <!-- <view
          class="memu-item"
          @tap="toMyCouponPage"
        >
          <view class="i-name">
            <image src="@/static/images/icon/myCoupon.png" />
            <text>我的优惠券</text>
          </view>
          <view class="arrowhead" />
        </view> -->
        <view class="memu-item" @tap="toAddressList">
          <view class="i-name">
            <image src="@/static/images/icon/myAddr.png" />
            <text>收货地址</text>
          </view>
          <view class="arrowhead" />
        </view>
        <!-- 客服电话 -->
        <view class="memu-item" @tap="showCustomerServiceModal">
          <view class="i-name">
            <image src="@/static/images/icon/myCoupon.png" />
            <text>客服电话</text>
          </view>
          <view class="arrowhead" />
        </view>
        <!-- <view class="memu-item" @tap="handleSettings">
          <view class="i-name">
            <text>账户设置</text>
          </view>
          <view class="arrowhead" />
        </view> -->
      </view>
      <!--end 列表项 -->

      <view v-if="isAuthInfo" class="log-out" @tap="logout">
        <view class="log-out-n">
          <text>退出登录</text>
        </view>
      </view>
    </view>
  </view>

  <!-- 客服电话弹框 -->
  <u-popup :show="showServiceModal" mode="bottom" @close="showServiceModal = false" round="20">
    <view class="service-modal">
      <view class="modal-header">
        <text class="modal-title">客服电话</text>
        <view class="modal-close" @tap="showServiceModal = false">
          <text class="close-icon">✕</text>
        </view>
      </view>
      <view class="modal-content">
        <view class="phone-item" @tap="makePhoneCall('051588287080')">
          <view class="phone-info">
            <text class="phone-number">0515-88287080</text>
            <text class="phone-type">座机</text>
          </view>
          <view class="call-btn">
            <text class="call-text">拨打</text>
          </view>
        </view>
        <view class="phone-item" @tap="makePhoneCall('19905107844')">
          <view class="phone-info">
            <text class="phone-number">199-0510-7844</text>
            <text class="phone-type">手机</text>
          </view>
          <view class="call-btn">
            <text class="call-text">拨打</text>
          </view>
        </view>
        <view class="phone-item" @tap="makePhoneCall('17751565498')">
          <view class="phone-info">
            <text class="phone-number">177-5156-5498</text>
            <text class="phone-type">手机</text>
          </view>
          <view class="call-btn">
            <text class="call-text">拨打</text>
          </view>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<script setup>
const picDomain = import.meta.env.VITE_APP_RESOURCES_URL;

const isAuthInfo = ref(false);
const loginResult = ref("");
const orderAmount = ref("");
const hadLogin = ref(false);
const avatarLoaded = ref(true);
const showServiceModal = ref(false);
/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  loginResult.value = uni.getStorageSync("userInfo");
  console.log(loginResult.value, "用户信息11");
  isAuthInfo.value = !!loginResult.value;
  hadLogin.value = uni.getStorageSync("hadLogin");
  // 加载订单数字
  if (isAuthInfo.value) {
    uni.showLoading();
    http
      .request({
        url: "/p/myOrder/orderCount",
        method: "GET",
        data: {},
      })
      .then(({ data }) => {
        uni.hideLoading();
        orderAmount.value = data;
      });
    showCollectionCount();
  }
});

const handleSettings = () => {
  uni.navigateTo({
    url: "/pages/settings/settings",
  });
};

const toAddressList = () => {
  uni.navigateTo({
    url: "/pages/delivery-address/delivery-address",
  });
};

/**
 * 显示客服电话弹框
 */
const showCustomerServiceModal = () => {
  showServiceModal.value = true;
};

/**
 * 拨打电话
 */
const makePhoneCall = (phoneNumber) => {
  showServiceModal.value = false; // 关闭弹框
  setTimeout(() => {
    uni.makePhoneCall({
      phoneNumber: phoneNumber,
      success: () => {
        console.log('电话拨打成功:', phoneNumber)
      },
      fail: (err) => {
        uni.showToast({
          title: '拨打电话失败',
          icon: 'none',
          duration: 2000
        })
        console.log('拨打电话失败:', err)
      }
    })
  }, 300); // 延迟300ms确保弹框关闭动画完成
};

const toOrderListPage = (e) => {
  const sts = e.currentTarget.dataset.sts;
  uni.navigateTo({
    url: "/pages/orderList/orderList?sts=" + sts,
  });
};

const collectionCount = ref(0);
/**
 * 查询所有的收藏量
 */
const showCollectionCount = () => {
  uni.showLoading();
  http
    .request({
      url: "/p/user/collection/count",
      method: "GET",
      data: {},
    })
    .then(({ data }) => {
      uni.hideLoading();
      collectionCount.value = data;
    });
};

/**
 * 我的收藏跳转
 */
const myCollectionHandle = () => {
  let url = "/pages/prod-classify/prod-classify?sts=5";
  const id = 0;
  const title = "我的收藏商品";
  if (id) {
    url += "&tagid=" + id + "&title=" + title;
  }
  uni.navigateTo({
    url,
  });
};

/**
 * 去登陆
 */
const toLogin = () => {
  uni.navigateTo({
    url: "/pages/accountLogin/accountLogin",
  });
};

/**
 * 退出登录
 */
const logout = () => {
  http
    .request({
      url: "/logOut",
      method: "post",
    })
    .then(() => {
      util.removeTabBadge();
      uni.removeStorageSync("loginResult");
      uni.removeStorageSync("Token");
      uni.removeStorageSync("hadLogin");
      uni.showToast({
        title: "退出成功",
        icon: "none",
      });
      // 重置页面状态变量
      loginResult.value = "";
      isAuthInfo.value = false;
      orderAmount.value = "";
      collectionCount.value = 0;
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/index/index",
        });
      }, 1000);
    });
};

const adminBaseApi = import.meta.env.VITE_ADMIN_BASE_API;
/**
 * 设置用户信息
 */
const onChooseAvatar = (e) => {
  const tempFilePath = e.detail.avatarUrl;
  console.log(adminBaseApi + "/admin/file/upload/element", tempFilePath);

  uni.uploadFile({
    url: adminBaseApi + "/admin/file/upload/element",
    filePath: tempFilePath,
    name: "file",
    formData: {
      type: "avatar",
    },
    header: {
      Authorization: uni.getStorageSync("Token"),
    },
    success: (uploadRes) => {
      const data = JSON.parse(uploadRes.data);
      console.log(data);

      if (data.code === "00000") {
        uni.showToast({
          title: "头像设置成功",
          icon: "success",
        });

        http
          .request({
            url: "/p/user/setUserInfo",
            method: "PUT",
            data: {
              avatarUrl: data.data,
              nickName: loginResult.value.nickName || "",
            },
          })
          .then(({ data }) => {
            uni.showToast({
              title: "昵称设置成功",
              icon: "success",
            });

            // 调用接口获取最新的用户信息
            return getUserInfo();
          })
          .then((userInfo) => {
            console.log(userInfo, "用户信息");
            // 更新本地用户信息
            loginResult.value = userInfo;
            uni.setStorageSync("loginResult", loginResult.value);
          })
          .catch(() => {
            uni.showToast({
              title: "设置失败",
              icon: "none",
            });
          });

        // 更新本地用户信息
        loginResult.value.pic = data.data;
        uni.setStorageSync("loginResult", loginResult.value);
      } else {
        uni.showToast({
          title: data.msg || "设置失败",
          icon: "none",
        });
      }
    },
    fail: (err) => {
      console.log(err);
      uni.showToast({
        title: "上传失败",
        icon: "none",
      });
    },
  });
};

const onNicknameBlur = (e) => {
  const newNickName = e.detail.value || e.target.value;
  console.log('昵称输入:', newNickName);

  if (newNickName && newNickName.trim()) {
    http
      .request({
        url: "/p/user/setUserInfo",
        method: "PUT",
        data: {
          avatarUrl: loginResult.value.pic || "",
          nickName: newNickName.trim(),
        },
      })
      .then(({ data }) => {
        uni.showToast({
          title: "昵称设置成功",
          icon: "success",
        });

        // 调用接口获取最新的用户信息
        return getUserInfo();
      })
      .then((userInfo) => {
        // 更新本地用户信息
        loginResult.value = userInfo;
        uni.setStorageSync("userInfo", loginResult.value);
        uni.setStorageSync("loginResult", loginResult.value);
      })
      .catch(() => {
        uni.showToast({
          title: "设置失败",
          icon: "none",
        });
      });
  }
};

/**
 * 获取用户信息
 */
const getUserInfo = () => {
  return http
    .request({
      url: "/p/user/userInfo",
      method: "GET",
    })
    .then(({ data }) => {
      console.log(data, "用户信息");
      uni.setStorageSync("userInfo", data);
      return data;
    });
};
</script>

<style scoped lang="scss">
@import "./user.scss";
</style>
